<?php

namespace App\Services;

use App\Models\Config;
use Illuminate\Support\Facades\Storage;

class ConfigService
{

    /**
     * 获取筛选配置分组
     * @return mixed
     */
    public static function getGroup()
    {
        $config = new Config();
        $list = $config::groupBy('group')->pluck('group');
        return self::groupHandle($list);
    }

    /**
     * 对配置分组数据进行处理 【 array(0=>'a');  =>  array('a'=>'a'); 】
     * @param $list
     * @return mixed
     */
    protected static function groupHandle($list)
    {
        foreach ($list as $key => $item){
            $list[$item] = $item;
            unset($list[$key]);
        }
        return $list;
    }

    /**
     * 刷新配置文件
     */
    public static function refreshFile()
    {
        $configModel = new Config();
        $config = [];
        foreach ($configModel->all() as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $config[$value['name']] = $value['value'];
        }

        file_put_contents(
            config_path('site.php'),
            '<?php' . "\n\nreturn " . var_export($config, true) . ";"
        );
    }
}